<template>
  <div v-loading="loading" class="home" style="min-height: 100%">
    <div style="width: 100%">
      <div class="left wrap mg-b">
        <el-input
          style="width: 120px"
          class="mg-r mg-b"
          size="mini"
          v-model="form.eventkey"
          placeholder="eventkey"
        ></el-input>
        <el-cascader
          size="mini"
          placeholder="选择媒体"
          v-model="media_data"
          :options="selectList.media_tree"
          :props="{ expandTrigger: 'hover' }"
          @change="mediaChange"
          class="mg-r mg-b"
          style="width: 120px"
        ></el-cascader>
        <el-date-picker
          style="width: 250px"
          size="mini"
          class="mg-r mg-b"
          v-model="created_at"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
        <el-select
          size="mini"
          v-model="form.activity_name"
          placeholder="活动名称"
          class="mg-r mg-b"
          style="width: 120px"
        >
          <el-option
            v-for="item in selectList.activity_name"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-select
          size="mini"
          v-model="form.product"
          placeholder="产品名称"
          class="mg-r mg-b"
          style="width: 120px"
        >
          <el-option
            v-for="item in selectList.product"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-select
          size="mini"
          v-model="form.register_type"
          placeholder="报名方式"
          class="mg-r mg-b"
          style="width: 120px"
        >
          <el-option
            v-for="item in selectList.register_type"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-select
          size="mini"
          v-model="form.city_lv"
          placeholder="城市分级"
          class="mg-r mg-b"
          style="width: 120px"
        >
          <el-option
            v-for="item in city_lv_list"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>

        <el-input
          size="mini"
          v-model="form.city_name"
          placeholder="城市名称"
          class="mg-r mg-b"
          style="width: 120px"
        ></el-input>
        <el-select
          size="mini"
          v-model="form.customer_type"
          placeholder="客户画像"
          class="mg-r mg-b"
          style="width: 120px"
        >
          <el-option
            v-for="item in selectList.customer_type"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-select
          size="mini"
          v-model="form.customer_lv"
          placeholder="客户等级"
          class="mg-r mg-b"
          style="width: 120px"
        >
          <el-option
            v-for="item in customer_lv_list"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-select
          size="mini"
          v-model="form.ad_source_name"
          placeholder="广告素材"
          class="mg-r mg-b"
          style="width: 120px"
        >
          <el-option
            v-for="item in selectList.ad_source_name"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-select
          size="mini"
          v-model="form.landing_page_name"
          placeholder="着陆页"
          class="mg-r mg-b"
          style="width: 120px"
        >
          <el-option
            v-for="item in selectList.landing_page_name"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <el-input
          style="width: 120px"
          size="mini"
          v-model="form.remark"
          placeholder="备注"
        ></el-input>
      </div>
      <div class="mg-b left">
        <el-button size="mini" @click="adSearch" type="primary">搜索</el-button>
        <el-button size="mini" @click="downloadExcel">导出excel</el-button>
        <LmsUpload class="mg-l" :header="tHeader" :filterVal="filterVal"  @onChange="excelUploadSuccess">
          <el-button size="mini">导入excel</el-button>
        </LmsUpload>
      </div>

      <div style="padding-bottom: 40px">
        <el-table :data="adTableData" stripe border style="width: 100%">
          <el-table-column fixed prop="eventkey" label="eventkey">
          </el-table-column>
          <el-table-column prop="media_tag" label="媒体大类"> </el-table-column>
          <el-table-column prop="media_tag1" label="媒体小类">
          </el-table-column>
          <el-table-column prop="media_name" label="媒体名称">
          </el-table-column>
          <el-table-column prop="ad_user_name" label="广告账户">
          </el-table-column>
          <el-table-column prop="ad_plan" label="广告计划"> </el-table-column>
          <el-table-column prop="ad_unit" label="广告单元"> </el-table-column>
          <el-table-column prop="key_word" label="关键字"> </el-table-column>
          <el-table-column prop="ad_agent" label="广告代理商"></el-table-column>
          <el-table-column prop="city_lv" label="城市分级"> </el-table-column>
          <el-table-column prop="city_name" label="城市名称"> </el-table-column>
          <el-table-column prop="activity_name" label="活动名称">
          </el-table-column>
          <el-table-column prop="product" label="产品名称"> </el-table-column>
          <el-table-column prop="register_type" label="报名方式">
          </el-table-column>
          <el-table-column prop="customer_lv" label="客户等级">
          </el-table-column>
          <el-table-column prop="customer_type" label="客户画像">
          </el-table-column>
          <el-table-column label="广告素材">
            <template #default="scope">
              <a :href="scope.row.ad_source_url" target="_blank">{{
                scope.row.ad_source_name
              }}</a>
            </template>
          </el-table-column>
          <el-table-column prop="landing_page_name" label="着陆页">
          </el-table-column>
          <el-table-column prop="remark" label="备注"> </el-table-column>
          <el-table-column prop="created_at" label="创建时间">
          </el-table-column>
          <el-table-column prop="updated_at" label="更新时间">
          </el-table-column>
          <el-table-column prop="cost" label="花费"> </el-table-column>
          <el-table-column prop="hook_enroll_count" label="报名数">
          </el-table-column>
          <el-table-column prop="hook_enroll_percent" label="报名成本">
          </el-table-column>
          <el-table-column prop="wechat_added_count" label="加私数">
          </el-table-column>
          <el-table-column prop="wechat_added_percent" label="加私成本">
          </el-table-column>
          <el-table-column prop="conversion_count" label="转化数">
          </el-table-column>
          <el-table-column prop="conversion_amount" label="GMV">
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template #default="scope">
              <el-button style="padding: 0" type="text" size="mini">
                <clipboard :text="scope.row.landing_page_url"></clipboard>
              </el-button>
              <el-button
                @click="showTableEditModal(scope.row)"
                class="mg-tb"
                size="mini"
                >编辑</el-button
              >
              <el-button @click="deleteAd(scope.row)" type="danger" size="mini"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          layout="prev, pager, next"
          @current-change="handleChange"
          :total="ad_total"
          :page-size="per"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog title="编辑广告" v-model="showEditModal"  width="700px">
      <el-form
        label-width="120px"
        :model="editForm"
        status-icon
        :rules="rules"
        ref="editFormRef"
      >
        <el-form-item label="eventkey" prop="eventkey">
          <el-input
            style="width: 200px"
            size="mini"
            v-model="editForm.eventkey"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="媒体" prop="media_rule">
          <el-cascader
            size="mini"
            placeholder="选择媒体"
            v-model="editForm.editMediaData"
            :options="selectList.media_tree"
            :props="{ expandTrigger: 'hover' }"
            @change="mediaChange"
            style="width: 520px"
          ></el-cascader>
        </el-form-item>
        <div class="left">
          <el-form-item label="广告计划">
            <el-input
              style="width: 200px"
              size="mini"
              v-model="editForm.ad_plan"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
          <el-form-item label="广告代理商" prop="ad_agent">
            <el-input
              style="width: 200px"
              size="mini"
              v-model="editForm.ad_agent"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
        </div>
        <div class="left">
          <el-form-item label="广告单元">
            <el-input
              style="width: 200px"
              size="mini"
              v-model="editForm.ad_unit"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
          <el-form-item label="关键字">
            <el-input
              style="width: 200px"
              size="mini"
              v-model="editForm.key_word"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
        </div>
        <el-form-item label="城市分级" prop="city_lv">
          <el-input
            style="width: 200px"
            size="mini"
            v-model="editForm.city_lv"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="城市名称" prop="city_name">
          <el-input
            style="width: 200px"
            size="mini"
            v-model="editForm.city_name"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <div class="left">
          <el-form-item label="活动名称" prop="activity_name">
            <el-input
              style="width: 200px"
              size="mini"
              v-model="editForm.activity_name"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
          <el-form-item label="产品名称" prop="product">
            <el-input
              style="width: 200px"
              size="mini"
              v-model="editForm.product"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
        </div>
        <div class="left">
          <el-form-item label="报名方式" prop="register_type">
            <el-input
              style="width: 200px"
              size="mini"
              v-model="editForm.register_type"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
          <el-form-item label="客户等级" prop="customer_lv">
            <el-select
              size="mini"
              v-model="editForm.customer_lv"
              placeholder="客户等级"
              class="mg-r mg-b"
              style="width: 200px"
            >
              <el-option
                v-for="item in customer_lv_list"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="用户画像" prop="customer_type">
          <el-input
            style="width: 200px"
            size="mini"
            v-model="editForm.customer_type"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <div class="left">
          <el-form-item label="广告素材">
            <el-input
              style="width: 200px"
              size="mini"
              v-model="editForm.ad_source_name"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
          <el-form-item label="着陆页">
            <el-input
              style="width: 200px"
              size="mini"
              v-model="editForm.landing_page_url"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
        </div>
        <el-form-item label="备注">
          <el-input
            style="width: 520px"
            size="mini"
            v-model="editForm.remark"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="花费">
          <el-input
            style="width: 200px"
            size="mini"
            v-model="editForm.cost"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditModal = false">取 消</el-button>
        <el-button type="primary" @click="editAd()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  // import oss from "../../utils/ali-oss";
  // oss.ossUploadFile("/pipup-lms/excel", option);
  import clipboard from "../../components/clipboard/index.vue";
  import LmsUpload from "../../components/xlsx-json-upload/index.vue";
  import _ from "lodash";
  import { inject, computed, defineComponent,ref,toRefs,onMounted,reactive,watch,getCurrentInstance } from 'vue'
  import addressJson from "../../utils/constant/address";
  import cityLv from "../../utils/constant/city_lv";
  import customerLv from "../../utils/constant/customer_lv";

  export default defineComponent({
    components: {
      clipboard,
      LmsUpload
    },
    setup() {
      const { proxy } = getCurrentInstance()

      var validateEditMedia = (rule, value, callback) => {
        let { media_tag, media_tag1, media_name, ad_user_name } = data.editForm;
        if (!(media_tag && media_tag1 && media_name && ad_user_name)) {
          callback(new Error("请选择"));
        } else {
          callback();
        }
      };
      const data = reactive({
        loading: true,
        fileList: [],
        upload_url: "",
        ad_total: 0,
        page: 1,
        per: 5,
        city_lv_list: cityLv,
        customer_lv_list: customerLv,
        showEditModal: false,
        form: {},
        editForm: {
          eventkey:"",
          editMediaData: [],
        },
        rules: {
          ad_source_url: [{ required: true, message: "请输入", trigger: "blur" }],
          eventkey: [{ required: true, message: "请输入", trigger: "blur" }],
          city_lv: [{ required: true, message: "请输入", trigger: "blur" }],
          city_name: [{ required: true, message: "请输入", trigger: "blur" }],
          activity_name: [{ required: true, message: "请输入", trigger: "blur" }],
          product: [{ required: true, message: "请输入", trigger: "blur" }],
          register_type: [{ required: true, message: "请输入", trigger: "blur" }],
          customer_lv: [{ required: true, message: "请输入", trigger: "blur" }],
          customer_type: [{ required: true, message: "请输入", trigger: "blur" }],
          media_rule: [
            { required: true, validator: validateEditMedia, trigger: "blur" },
          ],
        },
        created_at: [],
        tableData: [],
        adList: [],
        selectList: {
          activity_name: [],
          ad_source_name: [],
          ad_source_url: [],
          customer_lv: [],
          customer_type: [],
          landing_page_name: [],
          product: [],
          register_type: [],
        },
        toyList: [],
        select_list: {},
        media_data: [],
        media_tree: [],
        options: [],
        tHeader: ["eventkey","媒体大类","媒体小类","媒体名称","广告账户","广告计划","广告单元","关键字","广告代理商","城市分级","城市名称","活动名称","产品名称","报名方式","客户等级","客户画像","素材名字","素材地址","着陆页","备注","创建时间","更新时间","花费"],
        filterVal: ["eventkey","media_tag","media_tag1","media_name","ad_user_name","ad_plan","ad_unit","key_word","ad_agent","city_lv","city_name","activity_name","product","register_type","customer_lv","customer_type","ad_source_name","ad_source_url","landing_page_name","remark","created_at","updated_at","cost"],

        showTableEditModal(row) {
          data.editForm = { ...data.editForm, ...row };
          data.editForm.editMediaData = [
            data.editForm.media_tag,
            data.editForm.media_tag1,
            data.editForm.media_name,
            data.editForm.ad_user_name,
          ];
          data.showEditModal = true;
        },
        mediaChange(){},
        adTableList(list){
          return list.map((val) => ({
            ...val,
            hook_enroll_percent: +val.cost / +val.hook_enroll_count || 0,
            wechat_added_percent: +val.cost / +val.wechat_added_count || 0,
          }));
        },
        async excelUploadSuccess(result){
          data.loading = true;
          await proxy.$post("v1/ad/upload_excel_by_json",{list:result})
          await data.adListReload();
          proxy.$message("上传成功");
          data.loading = false;
        },
        async editAd(){
          proxy.$refs["editFormRef"].validate(async (valid) => {
            if (valid) {
              data.loading = true;
              const res = await proxy.$post("v1/ad/edit", data.editForm);
              data.loading = false;
              if (res.success) {
                data.adListReload();
                data.showEditModal = false;
                proxy.$message("修改成功");
              }
            }
          });
        },
        async deleteAd(ad){
          data.loading = true;
          await proxy.$post("v1/ad/delete", { id: ad.id });
          data.loading = false;
          data.adListReload();
        },
        async adListReload(){
          let params = { ...data.form, ...data.created_at_i };
          data.loading = true;
          let res = await proxy.$get("v1/ad/list", {
            ...params,
            page: data.page,
            per: data.per,
          });
          data.loading = false;
          data.adList = res.data.ad_list;
          data.ad_total = res.data.count;
        },
        arrayToTree(array, index = 0, parent){
          return _.uniqBy(
            array.filter((val) => val[index - 1] == parent),
            index
          )
            .filter((val) => val[0])
            .map((val) => ({
              value: val[index],
              label: val[index],
              children:
                val[index + 1] === undefined
                  ? undefined
                  : data.arrayToTree(array, index + 1, val[index]),
            }));
        },
        async adSelectReload(){
          data.loading = true;
          let res = await proxy.$get("v1/ad/select");
          data.loading = false;
          res.data.media_tree = data.arrayToTree(res.data.media);
          data.selectList = res.data;
        },
        async downloadExcel(){
          let msg = proxy.$message({
            message: "导出excel中请勿操作。。。",
            duration: 0,
          });
          data.loading = true;
          let res = await proxy.$post("v1/ad/download_excel");
          data.loading = false;
          // 导出excel
          const filterVal = data.filterVal
          const tHeader = data.tHeader
          import("../../utils/export2Excel").then((excel) => {
            excel.export_json_to_excel({
              header: tHeader,
              data: data.formatJson(filterVal, data.adTableList(res.data.ad_list)),
              filename: `广告列表`,
              autoWidth: true,
              bookType: "xlsx",
            });
            msg.close();
          });
        },
        async adSearch(){
          console.log("dsads")
          data.page = 1;
          data.adListReload();
        },
        handleChange(value){
          data.page = value;
          data.adListReload();
        },
        formatJson(filterVal, jsonData){
          return jsonData.map(r => filterVal.map(c => r[c]));
        },
        created_at_i:computed(() => {
          let val = data.created_at;
          return val.length
            ? {
                created_at_start: +(val[0].getTime() / 1000),
                created_at_end: +(val[1].getTime() / 1000),
              }
            : {};
        }),
        adTableData:computed(() => {
          return data.adTableList(data.adList)
        })
      })
      onMounted(async () => {
        console.log(addressJson)
        data.adListReload();
        data.adSelectReload();
      })
      watch(() => data.media_data, val => {
        data.form.media_tag = val[0];
        data.form.media_tag1 = val[1];
        data.form.media_name = val[2];
        data.form.ad_user_name = val[3];
      })
      watch(() => data.editForm.editMediaData, val => {
          data.editForm.media_tag = val[0];
          data.editForm.media_tag1 = val[1];
          data.editForm.media_name = val[2];
          data.editForm.ad_user_name = val[3];
      })
      
      return {
        ...toRefs(data),
      };
    }
  })
</script>
<style scoped>
  .modal-txt-l {
    line-height: 28px;
    width: 100px;
    text-align: right;
    margin-right: 20px;
  }
</style>
